/*
The MIT License

Copyright (c) 2010 Michael Webb

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
//EL
/**
 * @namespace Provides facilities for registering and looking up adapters
 */
CA.Adapters = {};
(function() {
	var registry = [];//private
	/**
	 * Method for adding an adaptation
	 * @name CA.Adapters.Register
	 * @function
	 * @param {string} from_ The Interface name being adapted from
	 * @param {string} to_ The Interface name being adapted to
	 * @param {Function} adapter The function that performs the adaptation
	 */
	CA.Adapters["Register"] = function(from_, to_, adapter) {
			registry.push( {
				'from_' : from_,
				'to_' : to_,
				'adapter' : adapter
			});
	};
	/**
	 * Adapts an object to a given interface
	 * @name CA.Adapters.Adapt
	 * @function
	 * @param {Object} obj The object being adapted
	 * @param {string} to_ The Interface name the object should be adapted to
	 * @param {boolean} ensure An optional parameter that can force a check on the adaptation to ensure it implements the interface
	 * @return {Object} The adapted object
	 */
	 CA.Adapters["Adapt"] = function(obj, to_, ensure) {
	 	var chk = CA.Interfaces["Check"];
		if (chk(obj, to_)) {
			return obj;
		}
		for ( var i = 0; i < registry.length; i++) {
			var entry = registry[i];
			if (to_ == entry["to_"]) {
				if (chk(obj, entry["from_"])) {
					var result = entry["adapter"](obj);
					if (ensure) {
						CA.Interfaces["Ensure"](result, to_);
					}
					return result;
				}
			}
		}
		throw new Error("No Adaptation Found");
	};
})();